package com.canbot.u05.versionupdate

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.PackageManager.NameNotFoundException
import android.net.ConnectivityManager
import android.net.Uri
import android.net.wifi.WifiManager
import android.os.Build
import android.text.TextUtils
import android.util.Log

import java.io.File

@Suppress("unused")
object RobotUtil {

    private var starttime: Long = 0

    val deviceVersion: String
        get() {
            var device_version = ""
            val bversion = Build.VERSION.INCREMENTAL
            if (bversion != null && bversion.contains(".")) {
                val arr = bversion.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                if (arr.isNotEmpty() && arr.size >= 3) {
                    device_version = arr[2].trim { it <= ' ' }
                }
            }
            return device_version
        }

    /**
     * 方法描述：获取本地userId方法
     *
     * @return
     * @see RobotUtil
     */
    @JvmStatic
    fun getUserId(context: Context): String? {
        val wifi = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        if (!wifi.isWifiEnabled) {
            wifi.isWifiEnabled = true
        }
        var info = wifi.connectionInfo
        var mac: String? = info.macAddress
        if (mac == null) {
            if (!wifi.isWifiEnabled) {
                wifi.isWifiEnabled = true
            }
            starttime = System.currentTimeMillis()
            while (System.currentTimeMillis() - starttime < 5000) {
                try {
                    Thread.sleep(1000)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }

                info = wifi.connectionInfo
                mac = info.macAddress
                if (mac != null) {
                    break

                }
            }
            if (mac == null) {
                Log.i(TAG, "getUserId失败 ")
                return null
            }

        }
        Log.i(TAG, "getUserId $mac")
        return mac.replace(":", "")
    }

    private const val TAG = "RobotUtil"

    /**
     * 检测wifi是否可用
     *
     * @param context
     * @return
     */
    @JvmStatic
    fun isStartWifi(context: Context): Boolean {
        try {
            val wm = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
            return WifiManager.WIFI_STATE_ENABLED == wm.wifiState
        } catch (e: Exception) {
        }

        return false
    }

    /**
     * 检测网络是否可用
     *
     * @return
     */
    @JvmStatic
    fun isNetworkConnected(context: Context): Boolean {
        val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val ni = cm.activeNetworkInfo
        return ni != null && ni.isConnectedOrConnecting
    }

    @JvmStatic
    fun install(file: File, context: Context) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent.action = Intent.ACTION_VIEW
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive")
        context.startActivity(intent)
    }

    /**
     * 获取已安装Apk文件的源Apk文件
     * 如：/data/app/my.apk
     */
    @JvmStatic
    fun getSourceApkPath(context: Context, packageName: String): String? {
        if (TextUtils.isEmpty(packageName)) {
            return null
        }
        try {
            val appInfo = context.packageManager.getApplicationInfo(packageName, 0)
            return appInfo.sourceDir
        } catch (e: NameNotFoundException) {
            e.printStackTrace()
        }

        return null
    }

    // 判断apk是否已安装
    @JvmStatic
    fun isPkgInstalled(ctx: Context, packageName: String): Boolean {
        val pm = ctx.packageManager
        try {
            pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES)
        } catch (e: NameNotFoundException) {
            Log.i(TAG, "$packageName 暂未安装")
            return false
        }

        return true
    }

}